<template>
  <el-dialog v-model="dialogVisible" title="新建文件" width="500px" @close="resetForm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="文件名" prop="name">
        <el-input v-model="form.name" placeholder="请输入文件名" />
      </el-form-item>

      <el-form-item label="文件类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型">
          <el-option
            v-for="type in fileTypes"
            :key="type"
            :label="type.toUpperCase()"
            :value="type"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标签">
        <el-select
          v-model="form.tags"
          placeholder="请选择标签"
          multiple
          filterable
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { getTags } from '@/api/tags'
import { createDoc } from '@/api/files'
import { useDocsStore } from '@/stores/DocsStore.js'

const props = defineProps({
  modelValue: Boolean,
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = ref(false)

watch(
  () => props.modelValue,
  (val) => (dialogVisible.value = val),
)
watch(dialogVisible, (val) => emit('update:modelValue', val))

const form = reactive({
  name: '',
  type: '',
  tags: [],
})

const formRef = ref()
const tags = ref([])
const fileTypes = ['docx', 'xlsx', 'pptx']

const rules = {
  name: [{ required: true, message: '文件名不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '请选择文件类型', trigger: 'change' }],
}

const fetchTags = async () => {
  try {
    const res = await getTags()
    tags.value = res.data
  } catch (err) {
    console.error('标签获取失败', err)
  }
}

const resetForm = () => {
  form.name = ''
  form.type = ''
  form.tags = []
}

const close = () => {
  emit('update:modelValue', false)
}

const submit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await createDoc(form)
      close()
      resetForm()
      useDocsStore().triggerRefresh()
    }
  })
}

onMounted(() => {
  fetchTags()
})
</script>
